In [2]:
import pandas as pd
import plotly.express as px
import numpy as np
import plotly.graph_objects as go

url = "https://raw.githubusercontent.com/bcaffo/MRIcloudT1volumetrics/master/inst/extdata/multilevel_lookup_table.txt"
multilevel_lookup = pd.read_csv(url, sep = "\t").drop(['Level5'], axis = 1)
multilevel_lookup = multilevel_lookup.rename(columns = {
    "modify"   : "roi", 
    "modify.1" : "level4",
    "modify.2" : "level3", 
    "modify.3" : "level2",
    "modify.4" : "level1"})
multilevel_lookup = multilevel_lookup[['roi', 'level4', 'level3', 'level2', 'level1']]
multilevel_lookup.head(100000)
Out[2]:
roi level4 level3 level2 level1
0 SFG_L SFG_L Frontal_L CerebralCortex_L Telencephalon_L
1 SFG_R SFG_R Frontal_R CerebralCortex_R Telencephalon_R
2 SFG_PFC_L SFG_L Frontal_L CerebralCortex_L Telencephalon_L
3 SFG_PFC_R SFG_R Frontal_R CerebralCortex_R Telencephalon_R
4 SFG_pole_L SFG_L Frontal_L CerebralCortex_L Telencephalon_L
... ... ... ... ... ...
278 Chroid_LVetc_L AnteriorLateralVentricle_L LateralVentricle_L Ventricle CSF
279 Chroid_LVetc_R AnteriorLateralVentricle_R LateralVentricle_R Ventricle CSF
280 IV_ventricle IV_ventricle IV_ventricle Ventricle CSF
281 ECCL_L inf_DPWM_L InferiorWM_L WhiteMatter_L Telencephalon_L
282 ECCL_R inf_DPWM_R InferiorWM_R WhiteMatter_R Telencephalon_R

283 rows × 5 columns

In [3]:
## Now load in the subject data
id = 127
subjectData = pd.read_csv("https://raw.githubusercontent.com/bcaffo/ds4bme_intro/master/data/kirby21.csv")
subjectData = subjectData.loc[(subjectData.type == 1) & (subjectData.level == 5) & (subjectData.id == id)]
subjectData = subjectData[['roi', 'volume']]
## Merge the subject data with the multilevel data
subjectData = pd.merge(subjectData, multilevel_lookup, on = "roi")
subjectData = subjectData.assign(icv = "ICV")
subjectData = subjectData.assign(comp = subjectData.volume / np.sum(subjectData.volume))
subjectData.head()
Out[3]:
roi volume level4 level3 level2 level1 icv comp
0 SFG_L 12926 SFG_L Frontal_L CerebralCortex_L Telencephalon_L ICV 0.009350
1 SFG_R 10050 SFG_R Frontal_R CerebralCortex_R Telencephalon_R ICV 0.007270
2 SFG_PFC_L 12783 SFG_L Frontal_L CerebralCortex_L Telencephalon_L ICV 0.009247
3 SFG_PFC_R 11507 SFG_R Frontal_R CerebralCortex_R Telencephalon_R ICV 0.008324
4 SFG_pole_L 3078 SFG_L Frontal_L CerebralCortex_L Telencephalon_L ICV 0.002227
In [4]:
df = subjectData
dff= pd.concat(
    [pd.DataFrame({'source': df.roi+'_3', 'target': df.level4+'_2', 'value':df.volume}),
     pd.DataFrame({'source': df.level4+'_2', 'target': df.level3+'_1', 'value':df.volume}),
     pd.DataFrame({'source': df.level3+'_1', 'target': df.level2, 'value':df.volume}),
     pd.DataFrame({'source': df.level2, 'target': df.level1, 'value':df.volume}),
     pd.DataFrame({'source': df.level1, 'target': df.icv, 'value':df.volume})],
     axis=0)

nodes = np.unique(dff[["source", "target"]], axis=None)
nodes = pd.Series(index=nodes, data=range(len(nodes)))

fig =  go.Figure(
    go.Sankey(
    node={"label": nodes.index},
    link={
    "source": nodes.loc[dff["source"]],
    "target": nodes.loc[dff["target"]],
    "value": dff["value"],}))

fig.update_layout(font_size=12, height=2000, width=1100)
fig.show()

fig =px.scatter(x=range(10), y=range(10))
fig.write_html("path/to/file.html")
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Input In [4], in <module>
     22 fig.show()
     24 fig =px.scatter(x=range(10), y=range(10))
---> 25 fig.write_html("path/to/file.html")

File /opt/tljh/user/lib/python3.9/site-packages/plotly/basedatatypes.py:3708, in BaseFigure.write_html(self, *args, **kwargs)
   3593 """
   3594 Write a figure to an HTML file representation
   3595 
   (...)
   3704     Representation of figure as an HTML div string
   3705 """
   3706 import plotly.io as pio
-> 3708 return pio.write_html(self, *args, **kwargs)

File /opt/tljh/user/lib/python3.9/site-packages/plotly/io/_html.py:542, in write_html(fig, file, config, auto_play, include_plotlyjs, include_mathjax, post_script, full_html, animation_opts, validate, default_width, default_height, auto_open, div_id)
    540 # Write HTML string
    541 if path is not None:
--> 542     path.write_text(html_str)
    543 else:
    544     file.write(html_str)

File /opt/tljh/user/lib/python3.9/pathlib.py:1285, in Path.write_text(self, data, encoding, errors)
   1282 if not isinstance(data, str):
   1283     raise TypeError('data must be str, not %s' %
   1284                     data.__class__.__name__)
-> 1285 with self.open(mode='w', encoding=encoding, errors=errors) as f:
   1286     return f.write(data)

File /opt/tljh/user/lib/python3.9/pathlib.py:1252, in Path.open(self, mode, buffering, encoding, errors, newline)
   1246 def open(self, mode='r', buffering=-1, encoding=None,
   1247          errors=None, newline=None):
   1248     """
   1249     Open the file pointed by this path and return a file object, as
   1250     the built-in open() function does.
   1251     """
-> 1252     return io.open(self, mode, buffering, encoding, errors, newline,
   1253                    opener=self._opener)

File /opt/tljh/user/lib/python3.9/pathlib.py:1120, in Path._opener(self, name, flags, mode)
   1118 def _opener(self, name, flags, mode=0o666):
   1119     # A stub for the opener argument to built-in open()
-> 1120     return self._accessor.open(self, flags, mode)

FileNotFoundError: [Errno 2] No such file or directory: 'path/to/file.html'
In [ ]:
 
In [ ]: